<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.filter.nickname"
        placeholder="请输入用户昵称"
        style="width: 200px;"
        col="6"
      ></el-input>
      <el-input
        v-model="listQuery.filter.phone"
        placeholder="请输入手机号码"
        style="width: 200px;"
        col="6"
      ></el-input>
      <el-input v-model="listQuery.filter.remark" placeholder="备注" style="width: 200px;" col="6"></el-input>
      <el-button type="primary" @click="searchData">查询</el-button>
    </div>

    <el-table
      :data="list"
      border
      style="width: 100%"
      v-loading="listLoading"
      fit
      highlight-current-row
    >
      <el-table-column fixed prop="id" label="id" width="100"></el-table-column>
      <el-table-column prop="wx_avatar" label=" 头像" min-width="120">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.wx_avatar"/>
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label=" 昵称" min-width="120"></el-table-column>
      <el-table-column prop="phone" label=" 手机号码" min-width="120"></el-table-column>
      <el-table-column prop="type" label=" 类型" min-width="120">
        <template slot-scope="scope">{{ typeFormat(scope.row.type)}}</template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="openDialog(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="destroy(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      :page="page"
      :limit="listQuery.limit"
      :pageSizes="pageSizes"
      @pagination="pageChange"
    ></pagination>

    <el-dialog :title="dialogTitle" :visible.sync="formDialogIsVisible">
      <el-form :model="formData" label-width="80px">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="table1">
            <el-form-item label="头像">
              <el-image style="width: 100px; height: 100px" :src="formData.wx_avatar"/>
            </el-form-item>

            <el-form-item label="昵称">
              <el-input v-model="formData.nickname" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="手机号码">
              <el-input v-model="formData.phone" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="备注">
              <el-input type="textarea" v-model="formData.remark" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="类型">
              <el-select v-model="formData.type" placeholder="请选择类型">
                <el-option
                  v-for="item in formSelections.types"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="实名认证" name="table2">

          </el-tab-pane>
          <el-tab-pane label="账户" name="table3">
            <div class="wallet_wrapper">
              <label>余额:</label>
              <span class="money">{{balance}}¥</span>
              <span class="modifyMoneyBtn" @click="reverseModifyBalance">修改余额</span>
            </div>

            <el-form  class="modify_balance_window demo-form-inline" v-show="modifyBalanceFlag" :inline="true">
              <el-form-item label="方式">
                <el-select v-model="balanceType" placeholder="请选择类型">
                  <el-option label="增加" :value="1" key="1"></el-option>
                  <el-option label="减少" :value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="金额">
                <el-input v-model.number="modifyBalance" inline="true" autocomplete="off" placeholder="请输入金额"></el-input>
              </el-form-item>
              <el-button type="primary" @click="updateBalance">确 定</el-button>
            </el-form>


            <template>
              <ul class="infinite-list bills_wrapper" v-infinite-scroll="load" style="overflow:auto">
                <div class="bills_item">
                  <span>时间</span>
                  <span class="label">金额</span>
                  <span>类型</span>
                </div>
                <li v-for="item in bills" class="infinite-list-item">
                  <div class="bills_item">
                    <span>{{item.time}}</span>
                    <span class="label">¥ {{item.active_amount}}</span>
                    <span>{{item.note}}</span>
                  </div>
                </li>
              </ul>
            </template>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formDialogIsVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {fetchList, update, destroy, getTypes} from "@/api/user";
  import {fetchList as fetchBills, getWalletByUserId, updateBalance} from "@/api/userWallet";
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

  export default {
    name: "user",
    components: {Pagination},
    data() {
      return {
        balance: 0,
        modifyBalanceFlag: false,
        count: 0,
        balanceType: 1,
        modifyBalance: 0,
        //  tab切换标志
        activeTab: "table1",
        list: null,
        total: 0,
        page: 1,
        pageSizes: [10, 20, 30],
        listLoading: true,
        listQuery: {
          offset: 0,
          limit: 10,
          filter: {
            nickname: null,
            phone: null,
            remark: null
          },
          options: {
            nickname: "like",
            phone: "like",
            remark: "like"
          }
        },
        bills: [],
        billsQuery: {
          page: 1,
          offset: 0,
          limit: 10,
          filter: {
            user_wallet_id: null,
          },
          options: {
            user_wallet_id: "=",
          }
        },
        formDialogIsVisible: false,
        formMode: "add",
        formSelections: {
          types: []
        },
        formData: {
          id: undefined,
          phone: undefined,
          wx_avatar: undefined,
          nickname: undefined,
          type: undefined,
          remark: undefined
        }
      };
    },
    computed: {
      dialogTitle() {
        return this.formMode === "add" ? "新增" : "编辑";
      }
    },
    created() {
      this.getList();
      this.init();
    },
    methods: {
      typeFormat(type) {
        let text = "未知";
        this.formSelections.types.forEach(item => {
          if (parseInt(item.id) === type) text = item.title;
        });
        return text;
      },
      async init() {
        let types = await getTypes();
        this.formSelections.types = types.data;
      },
      pageChange(data) {
        this.page = data.page;
        this.listQuery.limit = data.limit;
        this.listQuery.offset = (this.page - 1) * this.listQuery.limit;
        this.refresh(false);
      },
      getWalletByUserId(userId) {
        return getWalletByUserId(userId).then((res) => {
          this.balance = res.data.amount;
          this.billsQuery.filter.user_wallet_id = res.data.id;
        });
      },
      fetchBills(page) {
        this.billsQuery.offset = (this.billsQuery.page - 1) * this.listQuery.limit;
        fetchBills(this.billsQuery).then((res) => {
          let data = res.data;
          if (!data || data.list.length === 0) return;
          data.list.forEach((item) => {
            this.bills.push(item);
          });
          this.billsQuery.page++;
        });
      },
      load() {
        this.fetchBills(this.billsQuery.page);
      },
      openDialog(row) {
        this.activeTab = "table1";
        this.billsQuery.filter.user_wallet_id = null;
        if (!!row) {
          this.formMode = "edit";
          this.formData.id = row.id;
          this.formData.phone = row.phone;
          this.formData.nickname = row.nickname;
          this.formData.wx_avatar = row.wx_avatar;
          this.formData.type = row.type;
          this.formData.remark = row.remark;
          this.resetBills(row.id);
        } else {
          this.formMode = "add";
          this.formData.id = undefined;
          this.formData.phone = undefined;
          this.formData.nickname = undefined;
          this.formData.wx_avatar = undefined;
          this.formData.type = undefined;
          this.formData.remark = undefined;
        }
        this.formDialogIsVisible = true;
      },
      save() {
        let promise;
        this.listLoading = true;
        promise = update(this.formData);
        promise
          .then(() => {
            this.refresh();
          })
          .catch(() => {
            this.listLoading = false;
          });
      },
      async resetBills(id) {
        this.billsQuery.page = 1;
        this.billsQuery.offset = 0;
        this.balance = 0.00;
        this.bills = [];
        this.modifyBalance = 0;
        await this.getWalletByUserId(id);
        this.fetchBills(1);
      },
      reverseModifyBalance() {
        console.log(1);
        this.modifyBalanceFlag = !this.modifyBalanceFlag;
      },
      updateBalance() {
        updateBalance({
          type: this.balanceType,
          amount: this.modifyBalance,
          user_id: this.formData.id
        }).then((res) => {
          this.balance = res.data.amount;
          this.modifyBalanceFlag = !this.modifyBalanceFlag;
          this.$message({
            type: "success",
            message: "修改成功!"
          });
          this.resetBills(res.data.user_id);
        });
      },
      destroy(id) {
        this.$confirm("此操作将永久删除数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            this.listLoading = true;
            await destroy({id});
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          })
          .catch(error => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          })
          .finally(() => {
            this.refresh();
          });
      },
      searchData() {
        this.refresh(true);
      },
      refresh(isAll = false) {
        this.formDialogIsVisible = false;
        this.listLoading = false;
        if (isAll) {
          this.page = 1;
        }
        this.getList();
      },
      getList() {
        this.listLoading = true;
        fetchList(this.listQuery)
          .then(response => {
            let {data} = response;
            this.list = data.list;
            this.total = response.data.count;
            this.listLoading = false;
          })
          .catch(() => {
            this.listLoading = false;
          });
      },
    },
    watch: {
      page: function (newVluae, oldVluae) {
        this.listQuery.offset = (newVluae - 1) * this.listQuery.limit;
      }
    }
  };
</script>
<style lang="scss">
  .modify_balance_window {
    margin: 0 auto;
    padding: 10px;
    width: 50%;
    border: 1px solid #eaeaea;
    border-radius: 5px;
  }

  .wallet_wrapper {
    margin: 30px auto;
    text-align: center;
    color: #2c3e50;
    label {
      font-size: 14px;
    }

    .money {
      font-size: 20px;
      color: #E65D6E;
    }

    .modifyMoneyBtn {
      font-size: 14px;
      margin-left: 10px;
      color: #4AB7BD;
      cursor: pointer;
    }
  }

  .bills_wrapper {
    height: 150px;
    list-style: none;
    .bills_item {
      height: 30px;
      line-height: 30px;
      display: flex;

      span {
        flex: 1;
        text-align: center;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }

      .label {
        width: 100px;
        flex: 0 0 100px;
      }
    }
  }
</style>
